package com.ruoyi.web.controller.consumerAdmin;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.consumer.constance.AgentPoxyLevelEnum;
import com.ruoyi.consumer.domain.*;
import com.ruoyi.consumer.domain.bind.BindDTO;
import com.ruoyi.consumer.service.impl.*;
import com.ruoyi.consumer.utils.redis.CompanyCache;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.ruoyi.web.controller.tool.QRTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.ruoyi.consumer.constance.AgentPoxyLevelEnum.LEVEL_ONE;
import static com.ruoyi.consumer.constance.CompanyNameConstance.COMPANY_NAME;

/**
 * @author: lizhouwei
 * @ date : 2023/11/17
 * @description:
 */
@Api(tags = "代理关系后台相关接口")
@RestController
@RequestMapping("/api/relation")
public class RelationController {

    @Autowired
    private CUserServiceImpl userService;

    @Autowired
    private CLytxUserServiceImpl lytxUserService;

    @Autowired
    private CAgentRelationsServiceImpl agentService;

    @Autowired
    private CompanyCache companyCache;

    @Autowired
    private CCompanyServiceImpl companyService;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private CompanyBindServiceImpl bindService;

    @Autowired
    private QRTool qrTool;


    /**
     * 指定业务员到公司
     *
     * @param data
     * @return
     */
    @Transactional
    @ApiOperation("指定业务员到公司")
    @PostMapping("/bind-salesman")
    public AjaxResult bindStaffToCompany(@RequestBody BindDTO data) {
        Assert.notNull(data, "用户信息不能为空");
        String userName = data.getUserName();
        String userPhone = data.getUserPhone();
        System.out.println(data);
        Assert.notNull(userName, "用户姓名不能为空");
        Assert.notNull(userPhone, "用户手机号不能为空");

        //查询用户信息
        CUser cUser = new CUser();
        cUser.setUserName(userName);
        cUser.setUserPhone(userPhone);
        List<CUser> cUsers = userService.selectCUserList(cUser);
        if (cUsers.size() == 0) {
            return AjaxResult.error("用户不存在");
        }
        //查询公司信息
        if (cUsers.get(0).getCompanyId() != 0) {
            return AjaxResult.error("用户已绑定公司");
        } else {

            CAgentRelations agent = new CAgentRelations();
            agent.setUserId(cUsers.get(0).getUserId());
            agent.setSuperUserId(cUsers.get(0).getUserId());
            agent.setAgentLevel(LEVEL_ONE.getDescription());
            List<CAgentRelations> cAgentRelations = agentService.selectCAgentRelationsList(agent);
            System.out.println("=================================================");
            System.out.println("代理关系"+cAgentRelations);
            System.out.println("=================================================");
            if (!cAgentRelations.isEmpty() ) {
                if (cAgentRelations.get(0).getIsDelete() == 0)
                    return AjaxResult.error("该用户已经是业务员！");
            }
            agent.setAgentPath(cUsers.get(0).getUserId().toString());
            agent.setAgentLevel(AgentPoxyLevelEnum.LEVEL_ONE.getDescription());
            agentService.insertCAgentRelations(agent);
            String s = qrTool.YqmGenerate(String.valueOf(agent.getAgentId()));
            CAgentRelations agent1 = new CAgentRelations();
            agent1.setAgentId(agent.getAgentId());
            agent1.setQrCode(s);
            agentService.updateCAgentRelations(agent1);


            CLytxUser lytxUser = new CLytxUser();
            lytxUser.setUserId(cUsers.get(0).getUserId());
            lytxUser.setOpenid(cUsers.get(0).getOpenid());
            lytxUser.setUserName(cUsers.get(0).getUserName());
            lytxUser.setUserPhone(cUsers.get(0).getUserPhone());
            lytxUser.setCompanyId(cUsers.get(0).getCompanyId());
            lytxUser.setUserHeader(cUsers.get(0).getUserHeader());
            lytxUser.setUserNick(cUsers.get(0).getUserNick());
            lytxUserService.insertCLytxUser(lytxUser);
            companyCache.cacheCompanyInfo(cUsers.get(0).getUserId(), COMPANY_NAME);
            Long userAdminId = SecurityUtils.getUserId();
            SysUser sysUser = sysUserService.selectUserById(userAdminId);
            if (sysUser == null) {
                return AjaxResult.error("管理员不存在");
            }
            //查询当前管理员所处公司
            CCompany company = new CCompany();
            company.setCompanDept(Math.toIntExact(sysUser.getDeptId()));
            List<CCompany> cCompanies = companyService.selectCCompanyList(company);
            if (cCompanies.isEmpty()) {
                return AjaxResult.error("管理员所处公司不存在");
            }
            //绑定员工
            CompanyBind companyBind = new CompanyBind();
            companyBind.setConsumerId(cUsers.get(0).getUserId());
            if (!bindService.selectCompanyBindList(companyBind).isEmpty()) {
                return AjaxResult.error("用户已绑定公司");
            }
            companyBind.setDeptId(sysUser.getDeptId());
            bindService.insertCompanyBind(companyBind);
            //更新用户companyId
            CUser user = new CUser();
            user.setUserId(cUsers.get(0).getUserId());
            user.setCompanyId(cCompanies.get(0).getCompanyId());
            int i = userService.updateCUser(user);
            if (i > 0) {
                //缓存公司信息
                companyCache.cacheCompanyInfo(cUsers.get(0).getUserId(), cCompanies.get(0).getCompanyName());
                return AjaxResult.success("指定业务员成功");
            } else {
                return AjaxResult.error("指定业务员失败");
            }
        }
    }

    /**
     * 指定业务员到公司
     *
     * @param data
     * @return
     */
    @Transactional
    @ApiOperation("指定业务员到公司")
    @PostMapping("/bind-to-salesman/{userId}")
    public AjaxResult bindToCompany(@PathVariable Integer userId) {

        //查询用户信息
        CUser cUser = userService.selectCUserByUserId(userId);
        Assert.notNull(cUser, "用户不存在");
        //查询公司信息
        if (cUser.getCompanyId() != 0) {
            return AjaxResult.error("用户已绑定公司");
        } else {

            CAgentRelations agent = new CAgentRelations();
            agent.setUserId(cUser.getUserId());
            agent.setSuperUserId(cUser.getUserId());
            agent.setAgentLevel(LEVEL_ONE.getDescription());
            List<CAgentRelations> cAgentRelations = agentService.selectCAgentRelationsList(agent);
            System.out.println("=================================================");
            System.out.println("代理关系"+cAgentRelations);
            System.out.println("=================================================");
            if (!cAgentRelations.isEmpty() ) {
                if (cAgentRelations.get(0).getIsDelete() == 0)
                    return AjaxResult.error("该用户已经是业务员！");
            }
            agent.setAgentPath(cUser.getUserId().toString());
            agent.setAgentLevel(AgentPoxyLevelEnum.LEVEL_ONE.getDescription());
            agentService.insertCAgentRelations(agent);

            String s = qrTool.YqmGenerate(String.valueOf(agent.getAgentId()));
            CAgentRelations agent1 = new CAgentRelations();
            agent1.setAgentId(agent.getAgentId());
            agent1.setQrCode(s);
            agentService.updateCAgentRelations(agent1);

            CLytxUser lytxUser = new CLytxUser();
            lytxUser.setUserId(cUser.getUserId());
            lytxUser.setOpenid(cUser.getOpenid());
            lytxUser.setUserName(cUser.getUserName());
            lytxUser.setUserPhone(cUser.getUserPhone());
            lytxUser.setCompanyId(cUser.getCompanyId());
            lytxUser.setUserHeader(cUser.getUserHeader());
            lytxUser.setUserNick(cUser.getUserNick());
            lytxUserService.insertCLytxUser(lytxUser);
            companyCache.cacheCompanyInfo(cUser.getUserId(), COMPANY_NAME);
            Long userAdminId = SecurityUtils.getUserId();
            SysUser sysUser = sysUserService.selectUserById(userAdminId);
            if (sysUser == null) {
                return AjaxResult.error("管理员不存在");
            }
            //查询当前管理员所处公司
            CCompany company = new CCompany();
            company.setCompanDept(Math.toIntExact(sysUser.getDeptId()));
            List<CCompany> cCompanies = companyService.selectCCompanyList(company);
            if (cCompanies.isEmpty()) {
                return AjaxResult.error("管理员所处公司不存在");
            }
            //绑定员工
            CompanyBind companyBind = new CompanyBind();
            companyBind.setConsumerId(cUser.getUserId());
            if (!bindService.selectCompanyBindList(companyBind).isEmpty()) {
                return AjaxResult.error("用户已绑定公司");
            }
            companyBind.setDeptId(sysUser.getDeptId());
            bindService.insertCompanyBind(companyBind);
            //更新用户companyId
            CUser user = new CUser();
            user.setUserId(cUser.getUserId());
            user.setCompanyId(cCompanies.get(0).getCompanyId());
            int i = userService.updateCUser(user);
            if (i > 0) {
                //缓存公司信息
                companyCache.cacheCompanyInfo(cUser.getUserId(), cCompanies.get(0).getCompanyName());
                return AjaxResult.success("指定业务员成功");
            } else {
                return AjaxResult.error("指定业务员失败");
            }
        }
    }
}
